package com.tianyi.redis;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author tianyi
 * @Description 拦截器来解析的父类，将是否重复的判断给了子类来处理
 * @Date 2022 - 10 - 30
 **/
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatAnnotation annotation = method.getAnnotation(RepeatAnnotation.class);
            if (annotation != null) {
                if (this.isRepeatSubmit(request, annotation)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 500);
                    map.put("msg", annotation.message());
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().println(map);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交
     *
     * @param request    请求
     * @param annotation 注解
     * @return 是否有重得
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatAnnotation annotation);
}
